<?php
namespace Common\Logic;

/**
 * 房间逻辑
 * @modify trainyao 2016-01-05 创建
 */
class RoomLogic extends \Common\Controller\BaseController
{   
    /**
     * 获取房间数据,为了业务缓存封装
     * @modify trainyao 2016-01-07    创建
     * @modify trainyao 2016-08-29    增加补充房型信息参数
     * @param inetger $hotelId          客栈id
     * @param array     $roomId         房间id(s)
     * @return array   房间数据数组 [{id, name, roomfrom, isdirty, roomtype_id, hotelentity_id, (后面字段$withRoomType!=falseh时会有)roomtype_name, price}, {}, {}, ....]
     */
    public function getRoom($hotelId, $roomId = null, $withRoomType = false) {
        return $this->__singleGet('_getRoom', array($hotelId, $roomId, $withRoomType));
    }
    protected function _getRoom($hotelId, $roomId = null, $withRoomType = false) {
        $roomInfoModel = D('RoomInfo');
        $roomInfo = $roomInfoModel->getInfoByHotel($hotelId);

        if(empty($roomId)) {
            return $roomInfo;
        }
        if (!is_array($roomId)) {
            $roomId = explode(',', $roomId);
        }
        if (!is_array($roomId)) {
            return array();
        }

        foreach ($roomInfo as $index => $roomItem) {
            if(!in_array($roomItem['id'], $roomId)) {
                unset($roomInfo[$index]);
            }
        }
        unset($roomItem);

        $roomInfo = array_values($roomInfo);
        if ($withRoomType === false) {
            return $roomInfo;
        }

        // 补充房型信息
        $roomTypeIds = array_values(array_unique(array_column($roomInfo, 'roomtype_id')));
        $roomTypeModel = D('RoomType');
        $roomTypeInfo = $roomTypeModel->getInfo($roomTypeIds);
        $roomTypeInfo = count($roomTypeIds) == 1 ? array($roomTypeInfo) : $roomTypeInfo;
        $roomTypeInfo = getArrayValueAsIndex($roomTypeInfo, 'id');
        foreach ($roomInfo as &$roomItem) {
            $roomItem['roomtype_name'] = $roomTypeInfo[$roomItem['roomtype_id']]['name'];
            $roomItem['price'] = $roomTypeInfo[$roomItem['roomtype_id']]['price'];
        }
        unset($roomItem);

        return $roomInfo;
    }


    /**
     * 获取锁掌柜房间
     * @modify trainyao 2016-01-05 创建
     * @param  integer   $hotelId   客栈id
     * @param  mixin   $getEmpty   错误时候是否返回空数组 默认否
     * @return array      锁掌柜房间数据array(array('name' => '房间名', 'no' => '房间号', 'num' => '锁编号'))
     */
    public function getQrmRoom($hotelId, $getEmpty = false) {
        return $this->__singleGet('_getQrmRoom', array($hotelId, $getEmpty));
    }
    protected function _getQrmRoom($hotelId, $getEmpty = false) {
        $hotelEntityModel = D('HotelEntity');
        $hotelInfo = $hotelEntityModel->getInfo($hotelId);
        
        if (empty($hotelInfo)) {
            returnJson(403, 400, 'error');
        }
        /*if ($hotelInfo['status'] == IS_DELETE) {
            returnJson(403, 401, 'error');
        }*/
        if (empty($hotelInfo['communityno'])) {
            if($getEmpty !== false) {
                return array();
            }
            // 检查session内是否已经有数据存在
            $sessionCommunityData = session(C('QRM_AUTH_COMMUNITY_DATA'));
            if(!empty($sessionCommunityData)) {
                returnJson(403, 402, $sessionCommunityData);
            }
            
            returnJson(403, 402, 'error');
        }
        
        $communityNo = $hotelInfo['communityno'];
        
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('MANAGE_QRCODE_URL'));
        $client->setEncryptMode(3);
        
        $data = array(
            'flag' => 'uclbrt',
            'communityno' => $communityNo,
            'time' => time()
        );
        $result = $client->getRoomForMeizhu($data);
        $result = json_decode($result, true);

        if(is_array($result) && $result['httpstatus'] == 200) {
            return $result['data'];
        }
        return array();
    }

    /**
     * 根据开始结束时间,筛选能入住的房间信息,且包含可入住晚数
     * @modify trainyao 2016-07-06 创建
     * @param  integer   $hotelId   客栈ID
     * @param  string   $startTime 筛选时间开始 Y-m-d H:i:s
     * @param  string   $endTime   筛选时间结束 Y-m-d H:i:s
     * @param  mixin   $getDeleted   是否获取已删除房间,默认获取
     * @return array              信息数组 [{id,roomtype_id,name,canCheckinDays}, {},..
     */
    public function getCanCheckinRoomByDate($hotelId, $startTime, $endTime, $getDeleted = true) {
        $roomInfoModel = D('RoomInfo');
        $roomInfos = $roomInfoModel->getInfoByHotel($hotelId, null, $getDeleted);
        $startDateTimestamp = strtotime($startTime);
        $endDateTimestamp = strtotime($endTime);

        // 客栈时区
        $utc = new \Org\Util\UTC();
        $hotelEntityModel = D('HotelEntity')->getInfo($hotelId);
        //获取区号时区数据
        $HotelLogic = A('Common/Hotel', 'Logic');
        $universalTimeData = $HotelLogic->universalTimeList();
        $universalTimeData = getArrayValueAsIndex($universalTimeData, 'universalTimeId');
        $universalTimeTimezone = $universalTimeData[$hotelEntityModel['universaltime_id']]['universalTimeTimezone'];
        $universalTimeTimezone = isset($universalTimeTimezone) && !is_null($universalTimeTimezone) ? $universalTimeTimezone : 'GMT+8';
        foreach ($roomInfos as $roomId => &$roomInfo) {
            $roomInfo['starttime'] = $utc->toTimeZone($roomInfo['starttime'], 'Asia/Shanghai' , $universalTimeTimezone);
            // 校验是否在查询时间段内
            $startTimeNotIn = strtotime($roomInfo['starttime']) > $endDateTimestamp ? true : false;
            //$startTimeNotIn = $roomInfo['starttime'] > $endDateTimestamp ? true : false;
            $endTimeNotIn = false;
            if ($roomInfo['isdelete'] == IS_DELETE) {
                $endTimeNotIn = strtotime($roomInfo['endtime']) < $startDateTimestamp ? true : false;
            }
            if ($startTimeNotIn || $endTimeNotIn) {
                unset($roomInfos[$roomId]);
                continue;
            }
            // 算出查询时间段内,单个房间可贡献的可入住房间数
            if ($roomInfo['isdelete'] == NOT_DELETE) {
                // 未删除,不存在房间存在结束时间,查询结束日期作为结束日期,算可入住天数
                 $canCheckinStart = strtotime(substr($roomInfo['starttime'], 0, 10)) <= $startDateTimestamp ? $startTime : $roomInfo['starttime'];
                //$canCheckinStart = strtotime(date('Y-m-d',$roomInfo['starttime'])) <= $startDateTimestamp ? $startTime : date('Y-m-d H:i:s',$roomInfo['starttime']);
                $roomInfo['canCheckinDays'] = getRoomTotal($canCheckinStart, $endTime);
            } else {
                // 已删除,
                 $canCheckinStart = strtotime(substr($roomInfo['starttime'], 0, 10)) <= $startDateTimestamp ? $startTime : $roomInfo['starttime'];
                //$canCheckinStart = strtotime(date('Y-m-d',$roomInfo['starttime'])) <= $startDateTimestamp ? $startTime : date('Y-m-d H:i:s',$roomInfo['starttime']);
                $canCheckinEnd = strtotime(substr($roomInfo['endtime'], 0, 10)) >= $startDateTimestamp ? $endTime : $roomInfo['endtime'];
                $roomInfo['canCheckinDays'] = getRoomTotal($canCheckinStart, $canCheckinEnd);
            }
        }
        unset($roomInfo);

        return $roomInfos;
    }

    /**
     * 删除一个或多个房间
     * @modify trainyao 2016-01-05 创建
     * @modify trainyao 2016-04-25 修正为有效订单才会阻止删除房间
     * @param  integer   $hotelId   客栈id
     * @param  mixin   $roomIds   房间id(s)
     * @param  mixin   $multiTransMode   是否处在事务嵌套模式
     * @return boolean 
     */
    public function deleteInfo($hotelId, $roomIds, $multiTransMode = false) {
        $orderRoomModel = D('OrderRoom');

        // 检查房间是否有活跃状态订单
        $orderInfo = $orderRoomModel->getInfoByHotelRoom($hotelId, $roomIds);
        // 无效订单无法阻止房间删除
        foreach ($orderInfo as $index => $orderItem) {
            if (in_array($orderItem['status'], array(ORDER_CHECKOUTED, ORDER_CANCELED, ORDER_OUTDATED))) {
                unset($orderInfo[$index]);
            }
        }
        unset($orderItem);
        if(!empty($orderInfo)) {
            if($multiTransMode !== false) {
                $orderRoomModel->rollback();
            }
            returnJson(403, 300, 'error');
        }
        
        if($multiTransMode === false) {
            $orderRoomModel->startTrans();
        }
        $commit = true;

        // 删除上架房间
        $roomDetailModel = D('RoomDetail');
        $deleteResult = $roomDetailModel->deleteInfoByRoom($roomIds);
        if(empty($deleteResult)) {
            $commit = false;
        }

        // 删除房间数据
        if($commit) {
            $roomInfoModel = D('RoomInfo');
            $deleteResult = $roomInfoModel->deleteInfo($roomIds);
            if(empty($deleteResult)) {
                $commit = false;
            }
        }

        // 删除钟点房数据
        if($commit) {
            $hourRoomModel = D('HourRoom');
            $deleteResult = $hourRoomModel->deleteInfosInIds($roomIds);
            if(empty($deleteResult)) {
                $commit = false;
            }
        }

        // 删除长租房数据
        if($commit) {
            $longRoomModel = D('LongRoom');
            $deleteResult = $longRoomModel->deleteInfosInIds($roomIds);
            if(empty($deleteResult)) {
                $commit = false;
            }
        }

        //存在同步信息则删除
        $roomSynModel = D('RoomSyn');
        foreach ($roomIds as $roomId) {
            $roomSynModel->deleteInfo($roomId);
        }
        
        if($commit) {
            if($multiTransMode === false) {
                $orderRoomModel->commit();
            } else {
                return true;
            }
        } else {
            if($multiTransMode === false) {
                $orderRoomModel->rollback();
                returnJson(500, 510, 'error');
            } else {
                return false;
            }
        }
    }


    /**
     * 设置房间脏房干净房逻辑
     * @modify trainyao 2016-01-13 创建
     * @param  integer   $hotelId   客栈id
     * @param  integer   $roomId    房间id
     * @param  integer   $status    需要设置为干净/脏状态
     * @param  mixin   $multiTransMode  是否处在事务嵌套模式
     */
    public function setDirty($hotelId, $roomId, $dirtyStatus, $multiTransMode = false) {
        $roomInfoModel = D('RoomInfo');
        if ($multiTransMode === false) {
            $roomInfoModel->startTrans();
        }
        $commit = true;

        // 设置数据库
        $setResult = $roomInfoModel->setDirty($hotelId, $roomId, $dirtyStatus, true);
        if (!$setResult) {
            $commit = false;
        }

        // 在redis增加数据
        $redisHelperUtil = new \Org\Util\RedisHelper(null, null, 'meizhu');
        $redisHelperUtil->db(C('REDIS_ROOM_DB'));
        $timeStampLogArray = array();
        // 转换roomId格式
        if (!is_array($roomId)) {
            $roomId = explode(',', $roomId);
        }
        foreach ($roomId as $roomIdItem) {
            if ($commit) {
                $time = time();
                array_push($timeStampLogArray, array(
                    'value' => $roomIdItem,
                    'time' => $time,
                ));
                $setResult = $redisHelperUtil->table('dirty')->hMSet($hotelId . '_' .$roomIdItem . rand(), array(
                    'value' => 'd:' . $roomIdItem . ':' . $dirtyStatus . ':' . $time,
                ));
                if (empty($setResult)) {
                    $commit = false;
                }
            }
        }

        if ($commit) {
            if ($multiTransMode === false) {
                $roomInfoModel->commit();
            }

            return $timeStampLogArray;
        } else {
            if ($multiTransMode === false) {
                $roomInfoModel->rollback();
                returnJson(500, 506);
            } else {
                return false;
            }
        }
    }

    /**
     * 设置房间为维修房
     * @modify wenhui 2017-12-01 创建
     * @param  integer   $hotelId   客栈id
     * @param  integer   $roomTypeId    房态id
     * @param  integer   $roomId    房间id
     * @param  integer   $status    需要设置为干净/维修房
     * @param  integer   $startDate    开始时间戳
     * @param  integer   $endDate    结束时间戳
     */
    public function setService($hotelId, $roomTypeId, $roomId, $status, $startDate, $endDate) {
        $roomServiceModel = D('RoomService');

        // 校验时间合法性
        if (!is_null($startDate) && !is_null($endDate) && !isBeforeTime($startDate, $endDate, true)) {
            returnJson(403, 317, 'error');
        }

        // 查询子订单
        $orderLogic = A('Common/Order', 'Logic');
        $toDay = date('Y-m-d');
        $endDay = date('Y-m-d', strtotime('+1 month'));
        try {
            $orderInfo = $orderLogic->getSubOrder($hotelId, null, 'within', $toDay, $endDay, null, null, null, null, null, null, true);
            $orderInfo = $orderInfo['subOrder'];
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }

        if (!empty($orderInfo)) {
            $orderInfo = getArrayValueAsIndex($orderInfo, 'roominfo_id', true);
            // 设置维修房时间段内 是否存在订单
            if (isset($orderInfo[$roomId])) {
                foreach ($orderInfo[$roomId] as $key => $subOrder) {
                    if (in_array($subOrder['status'], [ORDER_BOOKED,ORDER_PAYED,ORDER_CHECKINED,ORDER_SHOULD_CHECKOUT])) {
                        $roomServiceDateArray = getDatesBetweenTime($startDate, $endDate, true);
                        // 是否夜审订单 ismidnightorder=1
                        if ($subOrder['ismidnightorder'] == 1) {
                            $orderDateArray = getDatesBetweenTime($subOrder['startdate'], $subOrder['enddate'], true);
                        } else {
                            $orderDateArray = getDatesBetweenTime($subOrder['startdate'], $subOrder['enddate']);
                        }
                        if (!empty(array_intersect($roomServiceDateArray, $orderDateArray))) {
                            returnJson(403, 515);
                        }
                    }
                }
                unset($subOrder);
            }
        }

        $startDate = strtotime($startDate);
        $endDate = strtotime($endDate);
        // 是否存在记录
        $oldData = $roomServiceModel->getServiceList($roomTypeId, $roomId, $hotelId);
        // 设置数据库
        if (empty($oldData)) {
            // 添加
            $saveResult = $roomServiceModel->addService($hotelId, $roomTypeId, $roomId, $status, $startDate, $endDate);
            if (!$saveResult) {
                returnJson(500, 508);
            }
        } else {
            // 修改
            $delete = $status == ROOM_CLEAN ? 1 : 0;
            $saveResult = $roomServiceModel->saveService($hotelId, $roomTypeId, $roomId, $status, $startDate, $endDate, $delete);
            if (!$saveResult) {
                returnJson(500, 506);
            }
        }

        return true;
    }

    /**
     * 修改同步房间标识
     * @modify trainyao 2016-04-25 创建
     * @modify zhangzhen 2017-01-10 添加RF卡支持
     * @param  integer   $hotelId   客栈id
     * @param  integer   $roomId    房间id
     * @param  integer   $roomFrom    房间来源,不传默认是锁掌柜(1)
     * @return boolean              执行结果
     */
    public function synRoom($hotelId, $roomId, $roomFrom = ROOMFROM_QRM) {
        $roomInfoModel = D('RoomInfo');
        $synRoomInfo = $roomInfoModel->getInfo($roomId, ROOMFROM_MEIZHU);
        if ($synRoomInfo['roomfrom'] !=  ROOMFROM_MEIZHU){
            returnJson(403, 202);
            return false;
        }

        $roomLogic = A('Common/Room', 'Logic');
        $qrmRoom = $roomLogic->getQrmRoom($hotelId, true);

        if (!empty($qrmRoom)) {
            $qrmRoomNumbers = array_column($qrmRoom, 'no');
            $roomRepeat = array_count_values($qrmRoomNumbers);
            if($roomRepeat[$synRoomInfo['name']]>1){
                returnJson(403, 309);
            }
            $qrmRoomLockType = array_column($qrmRoom, 'locktype');
            $key = array_search($synRoomInfo['name'], $qrmRoomNumbers);
            if ( $key !== false) {
                switch ($qrmRoomLockType[$key]) {
                    case '1':
                        $roomFrom = ROOMFROM_QRM;
                        break;
                    case '2':
                        $roomFrom = ROOMFROM_RF;
                        break;
                    case '3':
                        $roomFrom = ROOMFROM_RFANDQRM;
                    break;
                    case '4':
                        $roomFrom = ROOMFROM_OTHER;
                    break;
                    case '5':
                        $roomFrom = ROOMFROM_BLUETOOTH;
                    break;
                }
                $roomInfo = array(
                        'masterentity_id' => $qrmRoom[$key]['masterentity_id'],
                        'masterbuildinfo_id' => $qrmRoom[$key]['masterbuildinfo_id'],
                        'masterfloorinfo_id' => $qrmRoom[$key]['masterfloorinfo_id'],
                        'masterroominfo_id' => $qrmRoom[$key]['masterroominfo_id'],
                    );
            }
        }
        // 执行修改
        $roomInfoModel->startTrans();
        $commit = true;
        $synResult = $roomInfoModel->editInfo($hotelId, $roomId, NULL, $roomFrom, NULL, NULL);
        if (empty($synResult)) {
            $commit = false;
        }
        $roomSynModel = D('RoomSyn');
        if($commit){
            $synResult = $roomSynModel->addInfo($roomInfo['masterentity_id'], $roomInfo['masterbuildinfo_id'], $roomInfo['masterfloorinfo_id'], $roomInfo['masterroominfo_id'], $hotelId, $roomId);
            if (empty($synResult)) {
                $commit = false;
            }
        }
        if ($commit) {
            $roomInfoModel->commit();
            return true;
        } else {
            $roomInfoModel->rollback();
            returnJson(500, 506);
            return false;
        }
    }

    /**
     * 获取房间二维码
     * 方法会抛异常
     * @modify trainyao 2016-08-16 创建
     * @param  integer   $hotelId    客栈ID
     * @param  array   $roomData  [{roomId, minute, endTime}, {},]
     * @param  boolean   $lost   是否需要挂失房卡,批次号+1 ture: 需要 false: 不需要
     * @return array              {roomId => {type, cardString}, roomId => {type, cardString}, roomId => {type, cardString}...}
     */
    public function getQrcode($hotelId, $roomData, $lost) {
        // 获取bpass设置无同步房间的推广链接
        $bpassLogic = A('Common/Bpass', 'Logic');
        $bpassSetting = $bpassLogic->getSetting();
        $defaultLink = $bpassSetting['printdefaultstring'];


        // 获取客栈同步锁掌柜集群号
        $hotelLogic = A('Common/Hotel', 'Logic');
        $hotelInfo = $hotelLogic->getHotelByHotelId(array($hotelId));
        $getCardData = array();
        // 集群未同步,返回
        if (empty($hotelInfo[0]['communityno'])) {
            foreach ($roomData as $roomDataItem) {
                $getCardData[$roomDataItem['roomId']] = array(
                    'type' => PRINTQRCODE_TYPE_STRING,
                    'cardString' => $defaultLink,
                );
            }
            unset($roomDataItem);
            return $getCardData;
        }

        // 获取客栈房间信息
        $roomInfo = $this->getRoom($hotelId, array_column($roomData, 'roomId'));
        $roomInfo = getArrayValueAsIndex($roomInfo, 'id');

        // 调用RPC获取二维码
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('MANAGE_QRCODE_URL'));
        $client->setEncryptMode(3);
        $batchNo = time();
        foreach ($roomData as $roomDataItem) {
            if ($roomInfo[$roomDataItem['roomId']]['roomfrom'] == ROOMFROM_QRM || $roomInfo[$roomDataItem['roomId']]['roomfrom'] == ROOMFROM_RFANDQRM) {
                // 同步房间,前往获取房卡
                $minute = (strtotime($roomDataItem['enddate']) - strtotime($roomDataItem['startdate'])) / 60;
                $RPCData = array(
                    'userId' => getUserId(),
                    'from' => 3,
                    'flag' => 'uclbrt',
                    'communityNo' => $hotelInfo[0]['communityno'],
                    'room' => $roomInfo[$roomDataItem['roomId']]['name'],
                    'minute' => $minute,
                    'startTime' => $roomDataItem['startdate'],
                    'endTime' => $roomDataItem['enddate'],
                    'eletricTime' => $roomDataItem['enddate'],
                    'time' => time(),
                );
                if ($lost) {
                    $RPCData['printing'] = true;
                    $RPCData['batchNo'] = $batchNo;
                }
                $result = $client->getCardForMeizhu($RPCData);
                if (!is_string($result)) {
                    $getCardData[$roomDataItem['roomId']] = array(
                        'type' => PRINTQRCODE_TYPE_STRING,
                        'cardString' => $defaultLink,
                    );
                    continue;
                }
                $result = json_decode($result, true);
                if (!is_array($result)) {
                    $getCardData[$roomDataItem['roomId']] = array(
                        'type' => PRINTQRCODE_TYPE_STRING,
                        'cardString' => $defaultLink,
                    );
                    continue;
                }

                // 判断是否打印频繁
                if ($result['httpstatus'] != 200) {
                    if ($result['status'] == 600) {
                        throw new \Exception('403,509', 509);
                        return false;
                    } else {
                        $getCardData[$roomDataItem['roomId']] = array(
                            'type' => PRINTQRCODE_TYPE_STRING,
                            'cardString' => $defaultLink,
                        );
                        continue;
                    }
                } else {
                    $getCardData[$roomDataItem['roomId']] = array(
                        'type' => PRINTQRCODE_TYPE_QRCODE,
                        'cardString' => $result['data'],
                    );
                }
            } else {
                $getCardData[$roomDataItem['roomId']] = array(
                    'type' => PRINTQRCODE_TYPE_STRING,
                    'cardString' => $defaultLink,
                );
            }
        }
        unset($roomDataItem);

        return $getCardData;
    }

    /**
     * 检查(多个)房间是否在客栈内
     * @modify trainyao 2016-08-31 创建
     * @param  integer   $hotelId   客栈ID
     * @param  mixin   $roomId    房间ID(s)
     * @return boolean              是否在客栈内
     */
    public function checkRoomInHotel($hotelId, $roomId) {
        if (!is_array($roomId)) {
            $roomId = explode(',', $roomId);
        }

        $roomInfos = $this->getRoom($hotelId, $roomId);
        if (empty($roomInfos)) {
            return false;
        }

        return empty(array_diff($roomId, array_column($roomInfos, 'id')));
    }

    /**
     * 按房间获取预设价格
     * @add Paddy 2016-12-1 创建
     * @add zhangzhen 2017-5-18 钟点房
     * @add zhangz 2017-7-03 尾房
     * @param integer $hotelId 客栈ID
     * @param integer $startTime 结束时间戳
     * @param integer $endTime 结束时间戳
     */
    public function getRoomPrice($hotelId, $startTime, $endTime) {
        $roomInfoModel = D('RoomInfo');
        $roomInfo = $roomInfoModel->getInfoByHotel($hotelId);
        
        // 补充房型信息
        $roomTypeIds = array_values(array_unique(array_column($roomInfo, 'roomtype_id')));
        $roomTypeModel = D('RoomType');
        $roomTypeInfo = $roomTypeModel->getInfo($roomTypeIds);
        $roomTypeInfo = count($roomTypeIds) == 1 ? array(
            $roomTypeInfo
        ) : $roomTypeInfo;
        $roomTypeInfo = getArrayValueAsIndex($roomTypeInfo, 'id');
        
        $roomTypePriceModel = D('RoomTypePrice');
        $roomTypePriceList = $roomTypePriceModel->getPriceList($roomTypeIds, $startTime, $endTime);
        $priceData = array();
        foreach ($roomTypePriceList as $priceItem) {
            $priceData[$priceItem['roomtype_id'] . '_' . $priceItem['price_date']] = $priceItem['price'];
        }

        // 维修房数据
        $roomServiceModel = D('RoomService');
        $roomServiceList = $roomServiceModel->getServiceList($roomTypeIds, null, null, NOT_DELETE, true);
        $roomServiceList = getArrayValueAsIndex($roomServiceList, 'roominfo_id');

        //钟点房
        $hourRoomModel = D('HourRoom');
        $hourRoomInfos = $hourRoomModel->getInfosByHotel($hotelId);
        $hourRoomInfos = getArrayValueAsIndex($hourRoomInfos, 'roominfo_id');
        $hourPrices = D('HourPrice')->getInfosByHotel($hotelId);
        $hourPrices = getArrayValueAsIndex($hourPrices, 'roomtype_id');

        $longRoomModel = D('LongRoom');
        $longRoomInfos = $longRoomModel->getInfosByHotel($hotelId);
        $longRoomInfos = getArrayValueAsIndex($longRoomInfos, 'roominfo_id');

        $lastRoomPriceModel = D('LastRoomPrice');
        $nowadays = strtotime(date('Y-m-d'));
        $result = array();
        foreach ($roomInfo as $roomItem) {
            $typeInfo = $roomTypeInfo[$roomItem['roomtype_id']];
            $priceArray = array();
            $lastRoomPriceInfo = $lastRoomPriceModel->getInfoByRoomType($roomItem['roomtype_id'], $nowadays);
            if($lastRoomPriceInfo){
                $howManyDays = ($lastRoomPriceInfo['enddate'] - $nowadays)/86400;

                $startDate = $lastRoomPriceInfo['startdate'];
                $endDate = $lastRoomPriceInfo['enddate'];
                $startToEnd = ($endDate - $startDate)/86400;

                $start = $lastRoomPriceInfo['starttime'];
                $end = $lastRoomPriceInfo['endtime'];

                $currentTime = date('G');

                if($startToEnd > 0 && $start > $end){
                    $tempTime = 0;  
                }
            }

            for ($timestamp = $startTime; $timestamp <= $endTime; $timestamp += 86400) {
                if(empty($lastRoomPriceInfo)){
                    if (isset($priceData[$typeInfo['id'] . '_' . $timestamp])) {
                        $priceArray[]=array(
                            'timestamp'=>$timestamp,
                            'price'=>$priceData[$typeInfo['id'] . '_' . $timestamp]
                        );
                    } else {
                        $priceArray[]=array(
                            'timestamp'=>$timestamp,
                            'price'=>$typeInfo['price']
                        );
                    }
                }else{
                    //跨天数
                    if(isset($tempTime) && $timestamp == $nowadays){
                        if($start <= $currentTime && $currentTime < 24 || $tempTime < $end && $end > $currentTime){
                            $hasLastRoom = true;
                        }
                    }elseif ($start <= $currentTime && $currentTime < $end && $timestamp == $nowadays) {
                        $hasLastRoom = true;
                    }

                    if($hasLastRoom){
                        if($priceData[$typeInfo['id'] . '_' . $timestamp]){
                            $priceArray[] = array(
                                'timestamp' => $timestamp,
                                'price' => strval($priceData[$typeInfo['id'] . '_' . $timestamp] - $lastRoomPriceInfo['price']),
                            );
                        }else{
                            $priceArray[] = array(
                                'timestamp' => $timestamp,
                                'price' => strval($typeInfo['price'] - $lastRoomPriceInfo['price']),
                            );
                        }

                        $hasLastRoom = false; 
                    }else{
                        $priceArray[] = array(
                            'timestamp' => $timestamp,
                            'price' => $priceData[$typeInfo['id'] . '_' . $timestamp] ? $priceData[$typeInfo['id'] . '_' . $timestamp] : $typeInfo['price'],
                        );
                    }

                }
            }

            foreach ($priceArray as $key => &$priceItem) {
                // 是否维修房
                if (isset($roomServiceList[$roomItem['id']])) {
                    // 到结束日期 设置过的日期全变为 干净房
                    if ($roomServiceList[$roomItem['id']]['startdate'] <= $priceItem['timestamp'] && $priceItem['timestamp'] <= $roomServiceList[$roomItem['id']]['enddate']) {
                        $priceItem['isService'] = $roomServiceList[$roomItem['id']]['isservice'];
                    } else {
                        $priceItem['isService'] = ROOM_CLEAN;
                    }
                } else {
                    $priceItem['isService'] = ROOM_CLEAN;
                }
            }
            unset($priceItem);

            //添加钟点房价格
            if(isset($hourRoomInfos[$roomItem['id']])){
                $hourprice = $hourPrices[$roomItem['roomtype_id']];
            } else {
                $hourprice = [];
            }
            //添加长租房价格
            if(isset($longRoomInfos[$roomItem['id']])){
                $longprice = $typeInfo['longprice'];
            } else {
                $longprice = '0.00';
            }
            $result[] = array('room_id'=>(int)$roomItem['id'],'prices'=>$priceArray,'hourprice'=>$hourprice,'longprice'=>$longprice);
        }
        return $result;
    }

    /**
     * 按房型获取预设价格
     * @add zhangzhen 2017-5-26 房间
     * @param integer $hotelId 客栈ID
     * @param integer $startTime 结束时间戳
     * @param integer $endTime 结束时间戳
     * @return array
     */
    public function getRoomTypePrice($hotelId, $startTime, $endTime) {
        $roomInfoModel = D('RoomInfo');
        $roomInfo = $roomInfoModel->getInfoByHotel($hotelId);
        // 补充房型信息
        $roomTypeIds = array_values(array_unique(array_column($roomInfo, 'roomtype_id')));
        $roomTypeModel = D('RoomType');
        $roomTypeInfo = $roomTypeModel->getInfo($roomTypeIds);
        $roomTypeInfo = count($roomTypeIds) == 1 ? array(
            $roomTypeInfo
        ) : $roomTypeInfo;
        $roomTypeInfo = getArrayValueAsIndex($roomTypeInfo, 'id');
        $roomTypePriceModel = D('RoomTypePrice');
        $roomTypePriceList = $roomTypePriceModel->getPriceList($roomTypeIds, $startTime, $endTime);
        $priceData = array();
        foreach ($roomTypePriceList as $priceItem) {
            $priceData[$priceItem['roomtype_id'] . '_' . $priceItem['price_date']] = $priceItem['price'];
        }
        //钟点房
        $hourRoomModel = D('HourRoom');
        $hourRoomInfos = $hourRoomModel->getInfosByHotel($hotelId);
        $hourRoomInfos = getArrayValueAsIndex($hourRoomInfos, 'roomtype_id');
        $hourPrices = D('HourPrice')->getInfosByHotel($hotelId);
        $hourPrices = getArrayValueAsIndex($hourPrices, 'roomtype_id');
        $lastRoomPriceModel = D('LastRoomPrice');
        $nowadays = strtotime(date('Y-m-d'));
        $result = array();
        foreach ($roomTypeInfo as $roomTypeItem) {
            $priceArray = array();
            $lastRoomPriceInfo = $lastRoomPriceModel->getInfoByRoomType($roomTypeItem['id'], $nowadays);
            if($lastRoomPriceInfo){
                $startDate = $lastRoomPriceInfo['startdate'];
                $endDate = $lastRoomPriceInfo['enddate'];
                $startToEnd = ($endDate - $startDate)/86400;
                $start = $lastRoomPriceInfo['starttime'];
                $end = $lastRoomPriceInfo['endtime'];
                $currentTime = date('G');
                if($startToEnd > 0 && $start > $end ){
                    $tempTime = 0;
                }
            }
            for ($timestamp = $startTime; $timestamp <= $endTime; $timestamp += 86400) {
                if(empty($lastRoomPriceInfo)){
                    if (isset($priceData[$roomTypeItem['id'] . '_' . $timestamp])) {
                        $priceArray[]=array(
                            'timestamp'=>$timestamp,
                            'price'=>$priceData[$roomTypeItem['id'] . '_' . $timestamp]
                        );
                    } else {
                        $priceArray[]=array(
                            'timestamp'=>$timestamp,
                            'price'=>$roomTypeItem['price']
                        );
                    }
                }else{
                    //跨天数
                    if(isset($tempTime) && $timestamp == $nowadays){
                        if( $start <= $currentTime && $currentTime <= 23 || $tempTime <= $end && $end >= $currentTime){
                            $hasLastRoom = true;
                        }
                    }elseif ($start <= $currentTime && $currentTime <= $end && $timestamp == $nowadays) {
                        $hasLastRoom = true;
                    }else{
                        $priceArray[] = array(
                            'timestamp'=>$timestamp,
                            'price'=>$priceData[$roomTypeItem['id'] . '_' . $timestamp] ? $priceData[$roomTypeItem['id'] . '_' . $timestamp] : $roomTypeItem['price'],
                        );
                    }
                    if($hasLastRoom){
                        if($priceData[$roomTypeItem['id'] . '_' . $timestamp]){
                            $priceArray[] = array(
                                'timestamp'=>$timestamp,
                                'price'=>$priceData[$roomTypeItem['id'] . '_' . $timestamp] - $lastRoomPriceInfo['price'],
                            );
                        }else{
                            $priceArray[] = array(
                                'timestamp'=>$timestamp,
                                'price'=>$roomTypeItem['price'] - $lastRoomPriceInfo['price'],
                            );
                        }
                        $hasLastRoom = false;
                    }
                }
            }
            //添加钟点房价格
            if(isset($hourRoomInfos[$roomTypeItem['id']])){
                $hourprice = $hourPrices[$roomTypeItem['id']];
            } else {
                $hourprice = [];
            }
            //添加长租房价格
            $longprice = $roomTypeItem['id']['longprice'];
            $result[] = array('roomtype_id'=>(int)$roomTypeItem['id'],'prices'=>$priceArray,'hourprice'=>$hourprice,'longprice'=>$longprice);
        }
        return $result;
    }


    /**
     * 获取房型和房间
     * @add zhangzhen 2017-3-24 创建
     * @param integer $hotelId 客栈ID
     * @return array
     */
    public function getHourRoomList($hotelId) {
        $roomInfoModel = D('RoomInfo');
        // 房型信息
        $roomTypeModel = D('RoomType');
        $roomTypeInfos = $roomTypeModel->getInfoByHotel($hotelId);
        if (empty($roomTypeInfos)) {
            returnJson(403, 302);
        }
        $hourRoomModel = D('HourRoom');
        $hourRoomInfos = $hourRoomModel->getInfosByHotel($hotelId);

        $roomTypeIds = array_column($hourRoomInfos, 'roomtype_id');
        $returnData = [];

        foreach ($roomTypeInfos as $key => $roomTypeInfo) {
            if (in_array($roomTypeInfo['id'], $roomTypeIds)) {
                continue;
            }
            $returnData[$key]['roomTypeId'] = $roomTypeInfo['id'];
            $returnData[$key]['roomTypeName'] = $roomTypeInfo['name'];
            $roomInfo = $roomInfoModel->getInfoByRoomType($hotelId, $roomTypeInfo['id']);
            $returnData[$key]['room'] = $roomInfo;
        }
        
        return array_values($returnData);
    }

    /**
     * 获取房型和房间
     * @add zhangzhen 2017-3-24 创建
     * @param integer $hotelId 客栈ID
     * @return array
     */
    public function getLongRoomList($hotelId) {
        $roomInfoModel = D('RoomInfo');
        // 房型信息
        $roomTypeModel = D('RoomType');
        $roomTypeInfos = $roomTypeModel->getInfoByHotel($hotelId);
        if (empty($roomTypeInfos)) {
            returnJson(403, 302);
        }
        $longRoomModel = D('LongRoom');
        $longRoomInfos = $longRoomModel->getInfosByHotel($hotelId);

        $roomTypeIds = array_column($longRoomInfos, 'roomtype_id');
        $returnData = [];

        foreach ($roomTypeInfos as $key => $roomTypeInfo) {
            if (in_array($roomTypeInfo['id'], $roomTypeIds)) {
                continue;
            }
            $returnData[$key]['roomTypeId'] = $roomTypeInfo['id'];
            $returnData[$key]['roomTypeName'] = $roomTypeInfo['name'];
            $roomInfo = $roomInfoModel->getInfoByRoomType($hotelId, $roomTypeInfo['id']);
            $returnData[$key]['room'] = $roomInfo;
        }

        return array_values($returnData);
    }
}
